# -*- coding: utf-8 -*-

from odoo import http
from odoo.addons.weixin.api.session_manager import session_obj
import logging
from odoo.http import request
import random
import requests
import json
import datetime
import time

_logger = logging.getLogger(__name__)
cert = ("/odoo/apps/wanlong/wliot/static/cert/client.crt",
        "/odoo/apps/wanlong/wliot/static/cert/client.key")


class WliotIotController(http.Controller):

    @http.route('/wliot/iot/setSelfOpendegree', auth='none', csrf=False)
    def set_self_opendegree(self, **kw):
        ''' 设置手动控制开合度 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': self.get_partner_by_session_id(kw)
                })
            openDegreeValue = kw.get('openDegree')
            openDegreeValue = int(openDegreeValue)
            barcode = kw.get('barcode')
            operate_time = kw.get('operateTime')
            _logger.info(self.get_string_time(self.get_beijing_datetime(operate_time)))
            device = http.request.env['wliot.device'].sudo().search([
                ('barcode', '=', barcode)
            ])
            access_token = self.auth()
            version = http.request.env['ir.config_parameter'].get_param('version')
            app_id = http.request.env['ir.config_parameter'].get_param('iot_app_id')
            url = "https://180.101.147.89:8743/iocm/app/cmd/v1.4.0/deviceCommands?appId=%s" % app_id
            code_id = random.randint(0, 16777215)
            if len(str(device.IMEI)) == 15:
                model_num = str(device.IMEI) + '0'
            else:
                model_num = device.IMEI
            timeff = self.get_string_time(self.get_beijing_datetime(operate_time))
            _logger.info(timeff)
            _logger.info(timeff[0:2])
            _logger.info(timeff[2:4])
            _logger.info(timeff[4:6])
            _logger.info(timeff[6:8])
            _logger.info(timeff[8:10])
            _logger.info(timeff[10:12])
            params = {
                'deviceId': device.device_id,
                'expireTime': 0,
                'callbackUrl': 'https://wanlong.mxnet.cn:443/wliot/iot/commandRspData',
                'command': {
                    'serviceId': 'Switch',
                    'method': 'SET_SELF_OPEN_DEGREE',
                    # 'msgType': 'cloudReq',
                    'paras': {
                        'openDegreeValue': openDegreeValue,
                        'modelNum': model_num,
                        'timeff': timeff,
                        'codeID': code_id,
                        'cmdCode': 'selfOpenDegreeReq',
                        'version': version
                    }
                }
            }
            headers = {
                'app_key': app_id,
                'Authorization': 'Bearer %s' % access_token,
                'Content-Type': 'application/json'
            }
            response = requests.post(url=url, data=json.dumps(params), cert=cert, verify=False, headers=headers)
            # _logger.info(response.status_code)
            # _logger.info(response.content)
            _logger.info('*************')
            _logger.info(response.text)
            if response.status_code == 201:
                _logger.info("set_self_opendegree")
                response_text = json.loads(response.text)
                command_id = response_text.get('commandId')
                if response.status_code == 201:
                    http.request.env['wliot.device.command.log'].sudo().create({
                        'device': device.id,
                        'partner_id': partner.id,
                        'barcode': barcode,
                        'IMEI': device.IMEI,
                        'order_type': 'control',
                        'code': 04,
                        'code_id': code_id,
                        'command_id': command_id,
                        'send_code': True,
                        'response_code': False,
                        'status': 'send',
                        'self_open_degree': openDegreeValue,
                        'auto_open_degree_per20': 0,
                        'auto_open_degree_per40': 0,
                        'auto_open_degree_per60': 0,
                        'auto_open_degree_per80': 0,
                        'auto_open_degree_per100': 0,
                        # 'calibrate_time': None,
                        'frequence': 0,
                        'alarm': 0,
                        'calibrate_sensor': 0,
                        'calibrate_temp': 0,
                        'back_value': '',
                        'code_time': self.get_beijing_datetime2(operate_time)
                    })
                    return json.dumps({
                        'success': True,
                        'message': u'操作成功！',
                        'code': 200
                    })
                elif response.status_code == 403:
                    # message = response.content.get('error_desc')
                    return json.dumps({
                        'success': False,
                        'message': response.content,
                        'code': 400
                    })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 400,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/iot/setAutoOpendegree', auth='none', csrf=False)
    def set_auto_opendegree(self, **kw):
        ''' 设置自动控制开合度 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': self.get_partner_by_session_id(kw)
                })
            barcode = kw.get('barcode')
            operate_time = kw.get('operateTime')
            device = http.request.env['wliot.device'].sudo().search([
                ('barcode', '=', barcode)
            ])
            opendegree = kw.get('openDegrees')
            opendegree = str(opendegree)
            opendegrees = opendegree.split(',')
            access_token = self.auth()
            version = http.request.env['ir.config_parameter'].get_param('version')
            app_id = http.request.env['ir.config_parameter'].get_param('iot_app_id')
            url = "https://180.101.147.89:8743/iocm/app/cmd/v1.4.0/deviceCommands?appId=%s" % app_id
            code_id = random.randint(0, 16777215)
            params = {
                'deviceId': device.device_id,
                'expireTime': 0,
                'callbackUrl': 'https://wanlong.mxnet.cn:443/wliot/iot/commandRspData',
                'command': {
                    'serviceId': 'Switch',
                    'method': 'SET_AUTO_OPEN_DEGREE',
                    'paras': {
                        'openDegreeValue1': int(opendegrees[0]),
                        'openDegreeValue2': int(opendegrees[1]),
                        'openDegreeValue3': int(opendegrees[2]),
                        'openDegreeValue4': int(opendegrees[3]),
                        'openDegreeValue5': int(opendegrees[4]),
                        'modelNum': device.IMEI,
                        'time': self.get_string_time(self.get_beijing_datetime(operate_time)),
                        'codeID': code_id,
                        'cmdCode': 'autoOpenDegreeReq',
                        'version': version
                    }
                }
            }
            headers = {
                'app_key': app_id,
                'Authorization': 'Bearer %s' % access_token,
                'Content-Type': 'application/json'
            }
            response = requests.post(url=url, data=json.dumps(params), cert=cert, verify=False, headers=headers)
            # _logger.info(response.text)
            response_text = json.loads(response.text)
            command_id = response_text.get('commandId')
            if response.status_code == 201:
                http.request.env['wliot.device.command.log'].sudo().create({
                    'device': device.id,
                    'partner_id': partner.id,
                    'barcode': barcode,
                    'IMEI': device.IMEI,
                    'order_type': 'control',
                    'code': 06,
                    'code_id': code_id,
                    'command_id': command_id,
                    'send_code': True,
                    'response_code': False,
                    'status': 'send',
                    'self_open_degree': 0,
                    'auto_open_degree_per20': int(opendegrees[0]),
                    'auto_open_degree_per40': int(opendegrees[1]),
                    'auto_open_degree_per60': int(opendegrees[2]),
                    'auto_open_degree_per80': int(opendegrees[3]),
                    'auto_open_degree_per100': int(opendegrees[4]),
                    # 'calibrate_time': self.get_beijing_datetime(operate_time),
                    'frequence': 0,
                    'alarm': 0,
                    'calibrate_sensor': 0,
                    'calibrate_temp': 0,
                    'back_value': '',
                    'code_time': self.get_beijing_datetime2(operate_time)
                })
                return json.dumps({
                    'success': True,
                    'message': u'操作成功！',
                    'code': 200
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 400,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/iot/setDevice', auth='none', csrf=False)
    def set_device(self, **kw):
        ''' 设置检测频率，报警值，校准值 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': self.get_partner_by_session_id(kw)
                })
            barcode = kw.get('barcode')
            operate_time = kw.get('operateTime')
            device = http.request.env['wliot.device'].sudo().search([
                ('barcode', '=', barcode)
            ])
            frequencyValue = kw.get('frequencyValue')
            _logger.info(frequencyValue)
            alarmValue = kw.get('alarmValue')
            _logger.info(frequencyValue)
            calibrationValue = kw.get('calibrationValue')
            _logger.info(frequencyValue)
            access_token = self.auth()
            version = http.request.env['ir.config_parameter'].get_param('version')
            app_id = http.request.env['ir.config_parameter'].get_param('iot_app_id')
            url = "https://180.101.147.89:8743/iocm/app/cmd/v1.4.0/deviceCommands?appId=%s" % app_id
            code_id = random.randint(0, 16777215)
            params = {
                'deviceId': device.device_id,
                'expireTime': 0,
                'callbackUrl': 'https://wanlong.mxnet.cn:443/wliot/iot/commandRspData',
                'command': {
                    'serviceId': 'Setting',
                    'method': 'SET_DEVICE',
                    'paras': {
                        'frequencyValue': frequencyValue,
                        'alarmValue': alarmValue,
                        'calibrationValue': calibrationValue,
                        'modelNum': device.IMEI,
                        'time': self.get_string_time(self.get_beijing_datetime(operate_time)),
                        'codeID': code_id,
                        'cmdCode': 'setDeviceReq',
                        'version': version
                    }
                }
            }
            headers = {
                'app_key': app_id,
                'Authorization': 'Bearer %s' % access_token,
                'Content-Type': 'application/json'
            }
            response = requests.post(url=url, data=json.dumps(params), cert=cert, verify=False, headers=headers)
            _logger.info(response.text)
            # sensor_name = kw.get('sensorName')
            sensor_barcode = kw.get('sensor_barcode')
            senssor = http.request.env['wliot.ppm.sensor'].sudo().search([
                # ('name', '=', sensor_name),
                ('barcode', '=', sensor_barcode)
            ])
            response_text = json.loads(response.text)
            command_id = response_text.get('commandId')
            if response.status_code == 201:
                device.write({
                    'ppm_sensor_id': senssor.id
                })
                http.request.env['wliot.device.command.log'].sudo().create({
                    'device': device.id,
                    'partner_id': partner.id,
                    'barcode': barcode,
                    'IMEI': device.IMEI,
                    'order_type': 'setting',
                    'code': 8,
                    'code_id': code_id,
                    'command_id': command_id,
                    'send_code': True,
                    'response_code': False,
                    'status': 'send',
                    'self_open_degree': 0,
                    'auto_open_degree_per20': 0,
                    'auto_open_degree_per40': 0,
                    'auto_open_degree_per60': 0,
                    'auto_open_degree_per80': 0,
                    'auto_open_degree_per100': 0,
                    # 'calibrate_time': 0,
                    'frequence': frequencyValue,
                    'alarm': alarmValue,
                    'calibrate_sensor': calibrationValue,
                    'calibrate_temp': 0,
                    'back_value': '',
                    'code_time': self.get_beijing_datetime(operate_time)
                })
                return json.dumps({
                    'success': True,
                    'message': u'操作成功！',
                    'code': 200
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 400,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/iot/calibrateTemperature', auth='none', csrf=False)
    def calibrate_temperature(self, **kw):
        ''' 校准温度值 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': self.get_partner_by_session_id(kw)
                })
            barcode = kw.get('barcode')
            operate_time = kw.get('operateTime')
            device = http.request.env['wliot.device'].sudo().search([
                ('barcode', '=', barcode)
            ])
            temperatureValue = kw.get('temperatureValue')
            access_token = self.auth()
            version = http.request.env['ir.config_parameter'].get_param('version')
            app_id = http.request.env['ir.config_parameter'].get_param('iot_app_id')
            url = "https://180.101.147.89:8743/iocm/app/cmd/v1.4.0/deviceCommands?appId=%s" % app_id
            code_id = random.randint(0, 16777215)
            params = {
                'deviceId': device.device_id,
                'expireTime': 0,
                'callbackUrl': 'https://wanlong.mxnet.cn:443/wliot/iot/commandRspData',
                'command': {
                    'serviceId': 'Temperature',
                    'method': 'CALIBRATE_TEMPERATURE',
                    'paras': {
                        'temperatureValue': temperatureValue,
                        'modelNum': device.IMEI,
                        'time': self.get_string_time(self.get_beijing_datetime(operate_time)),
                        'codeID': code_id,
                        'cmdCode': 'temperatureReq',
                        'version': version
                    }
                }
            }
            headers = {
                'app_key': app_id,
                'Authorization': 'Bearer %s' % access_token,
                'Content-Type': 'application/json'
            }
            response = requests.post(url=url, data=json.dumps(params), cert=cert, verify=False, headers=headers)
            _logger.info(response.text)
            command_id = response.text.get('commandId')
            if response.status_code == 201:
                http.request.env['wliot.device.command.log'].sudo().create({
                    'device': device.id,
                    'partner_id': partner.id,
                    'barcode': barcode,
                    'IMEI': device.IMEI,
                    'order_type': 'setting',
                    'code': 12,
                    'code_id': code_id,
                    'command_id': command_id,
                    'send_code': True,
                    'response_code': False,
                    'status': 'send',
                    'self_open_degree': 0,
                    'auto_open_degree_per20': 0,
                    'auto_open_degree_per40': 0,
                    'auto_open_degree_per60': 0,
                    'auto_open_degree_per80': 0,
                    'auto_open_degree_per100': 0,
                    # 'calibrate_time': None,
                    'frequence': 0,
                    'alarm': 0,
                    'calibrate_sensor': 0,
                    'calibrate_temp': temperatureValue,
                    'back_value': '',
                    'code_time': self.get_beijing_datetime2(operate_time)
                })
                return json.dumps({
                    'success': True,
                    'message': u'操作成功！',
                    'code': 200
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 400,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/iot/updateDeviceDatas', auth='none', csrf=False)
    def updateDeviceDatas(self, **kw):
        ''' 订阅的设备数据批量变化 '''
        _logger.info("=============================")
        _logger.info(kw)

        return json.dumps({
            'success': True
        })

    @http.route('/wliot/iot/updateDeviceData', auth='none', csrf=False, type='json')
    def updateDeviceData(self, request, **kw):
        ''' 订阅的设备数据变化 '''
        try:
            data = request.jsonrequest
            _logger.info("updateDeviceData")
            _logger.info(data)
            notify_type = data.get('notifyType')
            notify_type = str(notify_type)
            if notify_type == 'deviceDataChanged':
                device_id = data.get('deviceId')
                device = http.request.env['wliot.device'].sudo().search([
                    ('device_id', '=', device_id)
                ])
                sensor = http.request.env['wliot.ppm.sensor'].sudo().search([
                    ('device', '=', device_id)
                ])
                product = http.request.env['wliot.product'].sudo().search([
                    ('id', '=', device.product_id.id)
                ])
                service = data.get('service')
                event_time = service.get('eventTime')
                datas = service.get('data')
                cmd_code = datas.get('cmdCode')
                cmd_code = str(cmd_code)
                msg_time = datas.get('msgTime')
                msg_time = self.get_beijing_datetime(msg_time)
                device_indicator_value = http.request.env['wliot.device.indicator.value'].sudo().search([
                    ('device', '=', device.id)
                ])
                service_type = service.get('serviceType')

                if service_type == 'ValveBasic':
                    if cmd_code == 'testReq':
                        test_data = datas.get('testData')
                        _logger.info(test_data)
                    else:
                        gas = datas.get('gas')
                        temperature = datas.get('temperature')
                        # 计算气体日平均值
                        sql = "select avg(a.normal_gas_value) as avg " \
                              "from wliot_device_indicator_log a " \
                              "where a.abnormal_gas=0 and a.device=%s and " \
                              "to_char(a.collection_date, 'YYYY-MM-DD')=%s " % (
                              device_id, datetime.datetime.now().date())
                        http.request.env.cr.execute(sql)
                        dicts = http.request.env.cr.dictfetchall()
                        if dicts:
                            gas_day_avg_value = dicts[0].get('avg')
                            # 修改设备当前值
                            if device_indicator_value:
                                device_indicator_value.sudo().write({
                                    'gas_present_value': gas,
                                    'gas_day_avg_value': gas_day_avg_value,
                                    'temp_present_value': temperature,
                                    'update_time': datetime.datetime.now()
                                })
                            else:
                                http.request.env['wliot.device.indicator.value'].sudo().create({
                                    'device': device.id,
                                    'gas_present_value': gas,
                                    'gas_day_avg_value': 0,
                                    'gas_calibrate_value': 0,
                                    'gas_alarm_value': 0,
                                    'temp_present_value': temperature,
                                    'temp_calibrate_value': 0,
                                    'temp_alarm_value': 0,
                                    'frequence': 0,
                                    'open_degree': 0,
                                    'running_status': 'normal',
                                    'open_degree_per20': 0,
                                    'open_degree_per40': 0,
                                    'open_degree_per60': 0,
                                    'open_degree_per80': 0,
                                    'open_degree_per100': 0,
                                    'update_time': datetime.datetime.now()
                                })
                            # 添加设备当前值日志
                            device_indicator_log = http.request.env['wliot.device.indicator.log']
                            if cmd_code == 'normalReq':
                                device_indicator_log.sudo().create({
                                    'device': device.id,
                                    'barcode': device.barcode,
                                    'IMEI': device.IMEI,
                                    'code': 1,
                                    # 'collection_date': datetime.datetime.now(),
                                    'collection_date': msg_time,
                                    'normal_gas_value': gas,
                                    'normal_temp_value': temperature,
                                    'abnormal_gas_value': 0,
                                    'abnormal_temp_value': 0,
                                    'repair_gas_value': 0,
                                    'repair_temp_value': 0,
                                    'code_time': msg_time
                                })
                                device.write({
                                    'status': 'activited',
                                    'running_status': 'normal',
                                    'lostin': False,
                                    'outrange': False,
                                    'alarm': False,
                                })
                            elif cmd_code == 'abnormalReq':
                                # 创建设备当前值日志
                                device_indicator_log.sudo().create({
                                    'device': device.id,
                                    'barcode': device.barcode,
                                    'IMEI': device.IMEI,
                                    'code': 2,
                                    'collection_date': datetime.datetime.now(),
                                    'normal_gas_value': 0,
                                    'normal_temp_value': 0,
                                    'abnormal_gas_value': gas,
                                    'abnormal_temp_value': temperature,
                                    'repair_gas_value': 0,
                                    'repair_temp_value': 0,
                                    'code_time': msg_time
                                })
                                # 创建报警消息
                                # 浓度报警
                                if (gas + product.ppm_calibration) > product.ppm_alarm:
                                    subject = 'conc_warning'
                                    subtype = "wliot.mt_iot_temp_warning"
                                    partner = self.env['res.partner'].sudo().search([
                                        ('id', '=', device.partner_id.id)
                                    ])
                                    partner_ids = partner.get_child()
                                    device.send_message(subject, subtype, partner_ids)
                                    # 修改设备运行状态
                                    if product.bottom_limit > gas or product.top_limit < gas:
                                        device.write({
                                            'running_status': 'lostin',
                                            'alarm': True,
                                            'outrange': True
                                        })
                                    else:
                                        device.write({
                                            'running_status': 'lostin',
                                            'alarm': True,
                                        })
                                # 温度报警
                                if (temperature + product.temp_calibration) > product.temp_alarm:
                                    subject = 'temp_warning'
                                    subtype = "wliot.mt_iot_conc_warning"
                                    partner = self.env['res.partner'].sudo().search([
                                        ('id', '=', device.partner_id.id)
                                    ])
                                    partner_ids = partner.get_child()
                                    device.send_message(subject, subtype, partner_ids)
                                    # 修改设备的运行状态
                                    device.write({
                                        'running_status': 'lostin',
                                        'alarm': True
                                    })
                            elif cmd_code == 'repairReq':
                                device_indicator_log.sudo().create({
                                    'device': device.id,
                                    'barcode': device.barcode,
                                    'IMEI': device.IMEI,
                                    'code': 3,
                                    'collection_date': datetime.datetime.now(),
                                    'normal_gas_value': 0,
                                    'normal_temp_value': 0,
                                    'abnormal_gas_value': 0,
                                    'abnormal_temp_value': 0,
                                    'repair_gas_value': gas,
                                    'repair_temp_value': temperature,
                                    'code_time': msg_time
                                })
                elif service_type == 'Switch':
                    if cmd_code == 'selfOpenDegreeRsp':
                        errcode = service.get('errcode')
                        self_opendegree = datas.get('openDegreeResult')
                        code_id = datas.get('codeID')
                        # 修改设备当前值
                        if device_indicator_value:
                            device_indicator_value.sudo().write({
                                'device': device.id,
                                'open_degree': self_opendegree,
                                'update_time': datetime.datetime.now()
                            })
                        else:
                            http.request.env['wliot.device.indicator.value'].sudo().create({
                                'device': device.id,
                                'gas_present_value': 0,
                                'gas_day_avg_value': 0,
                                'gas_calibrate_value': 0,
                                'gas_alarm_value': 0,
                                'temp_present_value': 0,
                                'temp_calibrate_value': 0,
                                'temp_alarm_value': 0,
                                'frequence': 0,
                                'open_degree': self_opendegree,
                                'running_status': 'normal',
                                'open_degree_per20': 0,
                                'open_degree_per40': 0,
                                'open_degree_per60': 0,
                                'open_degree_per80': 0,
                                'open_degree_per100': 0,
                                'update_time': datetime.datetime.now()
                            })
                        # 修改设备状态
                        device.write({
                            'mode': 'self',
                            'self_open_degree': self_opendegree
                        })
                        # 修改指令状态
                        device_command_log = self.env['wliot.device.command.log'].sudo().search([
                            ('device', '=', device_id),
                            ('command_id', '=', code_id),
                            ('order_type', '=', 'control'),
                            ('order', '=', 04)
                        ])
                        if errcode == 0:
                            status = 'work'
                        elif errcode == 1:
                            status = 'fail'
                        if device_command_log:
                            device_command_log.sudo().write({
                                'status': status,
                                'back_value': self_opendegree,
                            })
                    elif cmd_code == 'autoOpenDegreeRsp':
                        errcode = service.get('errcode')
                        auto_opendegree = datas.get('openDegreeResult')
                        code_id = datas.get('codeID')
                        # 修改设备当前值
                        if device_indicator_value:
                            device_indicator_value.sudo().write({
                                'device': device.id,
                                'open_degree': auto_opendegree,
                                'update_time': datetime.datetime.now()
                            })
                        else:
                            http.request.env['wliot.device.indicator.value'].sudo().create({
                                'device': device.id,
                                'gas_present_value': 0,
                                'gas_day_avg_value': 0,
                                'gas_calibrate_value': 0,
                                'gas_alarm_value': 0,
                                'temp_present_value': 0,
                                'temp_calibrate_value': 0,
                                'temp_alarm_value': 0,
                                'frequence': 0,
                                'open_degree': auto_opendegree,
                                'running_status': 'normal',
                                'open_degree_per20': 0,
                                'open_degree_per40': 0,
                                'open_degree_per60': 0,
                                'open_degree_per80': 0,
                                'open_degree_per100': 0,
                                'update_time': datetime.datetime.now()
                            })
                        # 修改设备状态
                        device.write({
                            'mode': 'auto',
                        })
                        # 修改指令状态
                        device_command_log = self.env['wliot.device.command.log'].sudo().search([
                            ('device', '=', device_id),
                            ('command_id', '=', code_id),
                            ('order_type', '=', 'control'),
                            ('order', '=', 06)
                        ])
                        if errcode == 0:
                            status = 'work'
                        elif errcode == 1:
                            status = 'fail'
                        if device_command_log:
                            device_command_log.sudo().write({
                                'status': status,
                                'back_value': auto_opendegree,
                            })
                elif service_type == 'Setting':
                    if cmd_code == 'setDeviceRsp':
                        errcode = service.get('errcode')
                        frequence = datas.get('frequencyResult')
                        alarm = datas.get('alarmResult')
                        calibration = datas.get('calibrationResult')
                        code_id = datas.get('codeID')
                        # 修改设备当前值
                        if device_indicator_value:
                            device_indicator_value.sudo().write({
                                'device': device.id,
                                'frequence': frequence,
                                'gas_alarm_value': alarm,
                                'gas_calibrate_value': calibration,
                                'update_time': datetime.datetime.now()
                            })
                        else:
                            http.request.env['wliot.device.indicator.value'].sudo().create({
                                'device': device.id,
                                'gas_present_value': 0,
                                'gas_day_avg_value': 0,
                                'gas_calibrate_value': calibration,
                                'gas_alarm_value': alarm,
                                'temp_present_value': 0,
                                'temp_calibrate_value': 0,
                                'temp_alarm_value': 0,
                                'frequence': frequence,
                                'open_degree': 0,
                                'running_status': 'normal',
                                'open_degree_per20': 0,
                                'open_degree_per40': 0,
                                'open_degree_per60': 0,
                                'open_degree_per80': 0,
                                'open_degree_per100': 0,
                                'update_time': datetime.datetime.now()
                            })
                        # 修改指令状态
                        device_command_log = self.env['wliot.device.command.log'].sudo().search([
                            ('device', '=', device_id),
                            ('command_id', '=', code_id),
                            ('order_type', '=', 'setting'),
                            ('order', '=', 8)
                        ])
                        if errcode == 0:
                            status = 'work'
                        elif errcode == 1:
                            status = 'fail'
                        if device_command_log:
                            device_command_log.sudo().write({
                                'status': status,
                                'back_value': frequence,
                            })
            return json.dumps({
                'success': True,
                'code': 200
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/iot/commandRspData', auth='none', csrf=False, type='json')
    def commandRspData(self, request, **kw):
        try:
            json_data = request.jsonrequest
            _logger.info("commandRspData")
            _logger.info(json_data)
            command_id = json_data.get('commandId')
            device_id = json_data.get('deviceId')
            device = http.request.env['wliot.device'].sudo().search([
                ('device_id', '=', device_id)
            ], limit=1)
            command = http.request.env['wliot.device.command.log'].sudo().search([
                ('command_id', '=', command_id)
            ])
            result = json_data.get('result')
            command_status = result.get('resultCode')
            command_status = str(command_status)
            # command_status = 'FAILED'
            _logger.info(command_status)
            if command_status == 'DEFAULT':
                # 未下发
                command_status = 'send'
            elif command_status == 'EXPIRED':
                # 已经过期
                command_status = 'fail'
            elif command_status == 'TIMEOUT':
                # 执行超时
                command_status = 'fail'
            elif command_status == 'CANCELED':
                # 撤销执行
                command_status = 'fail'
            elif command_status == 'FAILED':
                # 执行失败
                command_status = 'fail'
            elif command_status == 'SUCCESSFUL':
                # 执行成功
                command_status = 'work'
            if command:
                command.sudo().write({
                    'status': command_status
                })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    def get_partner_by_session_id(self, kw):
        '''检查session是否过期，并根据session_id返回该微信号可以查看的客户'''
        session_id = kw.get('SessionID')
        if not session_id:
            return {
                'success': False,
                'code': 400,
                'msg': u'请传入session_id！',
            }
        open_id = session_obj.pydis.get(session_id)
        if not open_id:
            return {
                'success': False,
                'code': 900,
                'msg': u'sessoin已过期，请重新获取！',
            }
        wechat_recs = http.request.env['weixin.user'].sudo().search([('open_id', '=', open_id)])
        partner = http.request.env['res.partner'].sudo().search([('id', '=', wechat_recs.partner_id.id)])
        return partner

    def check_phone_legal(self, phone):
        '''是否存在该电话的客户，若存在则返回该客户'''
        records = http.request.env['res.partner'].sudo().search([
            # ('partner_type', '=', 'customer'),
            ('phone', '=', phone)
        ])
        if not records:
            return {
                'success': False,
                'msg': u'不存在电话为%s的客户！' % phone,
            }
        else:
            return {
                'success': True,
                'value': records,
            }

    def auth(self):
        ''' 鉴权 '''
        app_id = http.request.env['ir.config_parameter'].get_param('iot_app_id')
        secret = http.request.env['ir.config_parameter'].get_param('iot_secret')
        params = {
            'appId': app_id,
            'secret': secret
        }
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        response = requests.post(url="https://180.101.147.89:8743/iocm/app/sec/v1.1.0/login", data=params, cert=cert,
                                 verify=False, headers=headers)
        response = json.loads(response.text)
        access_token = response.get('accessToken')
        return access_token

    def get_beijing_datetime(self, uploadtime):
        return (datetime.datetime.strptime(time.strftime('%Y-%m-%d %H:%M:%S',
                                                         time.localtime(int((long(uploadtime)) * (
                                                                 10 ** (10 - len(str(uploadtime))))))),
                                           '%Y-%m-%d %H:%M:%S') + datetime.timedelta(hours=8)).strftime(
            '%Y-%m-%d %H:%M:%S')

    def get_beijing_datetime2(self, uploadtime):
        return (datetime.datetime.strptime(time.strftime('%Y-%m-%d %H:%M:%S',
                                                         time.localtime(int((long(uploadtime)) * (
                                                                 10 ** (10 - len(str(uploadtime))))))),
                                           '%Y-%m-%d %H:%M:%S')).strftime(
            '%Y-%m-%d %H:%M:%S')

    def get_string_time(self, bjtime):
        bjtime = str(bjtime)
        year = bjtime[2:4]
        month = bjtime[5:7]
        day = bjtime[8:10]
        hour = bjtime[11:13]
        minute = bjtime[14:16]
        second = bjtime[17:19]
        s = '%s%s%s%s%s%s' % (year, month, day, hour, minute, second)
        _logger.info(s)
        return s
